<template>
  <el-dialog
    :title="props.title"
    @close="onClose"
    v-model="visible"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="main">
      <el-scrollbar ref="scrollRef" height="650px" :min-size="10">
        <div class="title">基本设置</div>
        <el-form
          :disabled="props.title.includes('详情')"
          :model="formParams"
          ref="formRef"
          :rules="rules"
          label-width="140px"
        >
          <el-form-item label="城市标签" prop="cityName">
            <el-select
              @change="handleChangeCity"
              v-model="formParams.cityName"
              style="width: 320px"
              clearable
              fit-input-width
              placeholder="请选择"
              :disabled="!props.title.includes('设置')"
            >
              <el-option
                v-for="item in cityNameOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动名称" prop="activityName">
            <el-input
              v-model.trim="formParams.activityName"
              placeholder="请输入活动名称,最多16字"
              maxlength="16"
              clearable
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item label="参与点位" prop="position">
            <el-radio-group
              @change="positionChange(1)"
              v-model="formParams.position"
              :disabled="!props.title.includes('设置')"
            >
              <div class="title2">普通点位</div>
              <el-radio :value="1" :label="1"> 全部 </el-radio>
              <el-radio :value="2" :label="2">
                指定点位
                <el-select
                  v-show="formParams.position === 2"
                  style="width: 240px"
                  v-model="formParams.positionIdList"
                  multiple
                  filterable
                  clearable
                  fit-input-width
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="请选择"
                  :disabled="!props.title.includes('设置')"
                  @change="positionChange(0)"
                >
                  <el-option
                    v-for="item in positionOptions"
                    :key="item.positionId"
                    :label="item.positonName"
                    :value="item.positionId"
                  />
                </el-select>
              </el-radio>
              <span style="margin-right: 100px"></span>

              <div class="title2">特殊点位</div>

              <el-radio :value="3" :label="3"> 全部 </el-radio>
              <el-radio :value="4" :label="4">
                指定点位
                <el-select
                  v-show="formParams.position === 4"
                  style="width: 240px"
                  v-model="formParams.positionIdList"
                  multiple
                  filterable
                  clearable
                  fit-input-width
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="请选择"
                  :disabled="!props.title.includes('设置')"
                  @change="positionChange(0)"
                >
                  <el-option
                    v-for="item in specialPositionTypeOptions"
                    :key="item.positionId"
                    :label="item.positonName"
                    :value="item.positionId"
                  />
                </el-select>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邀请奖励" prop="hostCouponId">
            <el-tree-select
              accordion
              v-model="formParams.hostCouponId"
              :data="inviterOptions"
              :render-after-expand="false"
              style="width: 320px"
              filterable
            />
          </el-form-item>
          <el-form-item label="活动时间" prop="huodongshijian">
            <div>
              <el-date-picker
                v-model="formParams.huodongshijian"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                date-format="YYYY-MM-DD"
                time-format="HH:mm"
                style="width: 320px"
                :disabled-date="disabledDate"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </div>
          </el-form-item>

          <el-form-item label="奖励规则" required>
            <span>订单完成后奖励自动发放</span>
          </el-form-item>
          <el-form-item label="邀请好友规则" prop="ruleDescribe">
            <div style="width: 100%">
              <el-input
                v-model="formParams.ruleDescribe"
                style="width: 320px"
                :autosize="{ minRows: 3, maxRows: 8 }"
                type="textarea"
                maxlength="1000"
                placeholder="请输入内容"
                show-word-limit
              />
            </div>
          </el-form-item>
          <div class="title">活动设置</div>
          <el-form-item label="上传背景" prop="backgroundImg">
            <div
              ><ImageUploadByType
                v-model="formParams.backgroundImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
              />请上传大小不超过10MB，格式为png/jpg/jpeg的文件，图片推荐尺寸750px*600px</div
            >
          </el-form-item>
          <el-form-item label="按钮文字" prop="buttonName">
            <el-input
              v-model.trim="formParams.buttonName"
              placeholder="请输入按钮文字，最多十字"
              maxlength="10"
              clearable
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item label="活动规则" prop="activityRule">
            <div style="width: 100%">
              <el-input
                v-model="formParams.activityRule"
                style="width: 320px"
                :autosize="{ minRows: 3, maxRows: 8 }"
                type="textarea"
                maxlength="1000"
                placeholder="请输入内容"
                show-word-limit
              />
            </div>
          </el-form-item>
          <div class="title">分享设置</div>
          <el-form-item label="分享标题" prop="shareTitle">
            <el-input
              v-model.trim="formParams.shareTitle"
              placeholder="请输入标题名称，最多20字"
              maxlength="20"
              clearable
              style="width: 320px"
            />
          </el-form-item>
          <el-form-item label="上传图片" prop="shareImg">
            <div
              ><ImageUploadByType
                v-model="formParams.shareImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
                validateAspectRatio5To4
              />请上传大小不超过10MB，格式为png/jpg/jpeg的文件，图片的比例为5:4, 如500px*400px</div
            >
          </el-form-item>
          <el-form-item label="上传分享页面背景" prop="shareBackgroundImg">
            <div
              ><ImageUploadByType
                v-model="formParams.shareBackgroundImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
                :imagePx="[750, 1800]"
              />请上传大小不超过10MB，格式为png/jpg/jpeg的文件，图片推荐尺寸750px*1800px</div
            >
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <template #footer v-if="!props.title.includes('详情')">
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  addIntivationApi,
  editIntivationApi,
  getAllCouponListApi,
  getInvitationDetailApi
} from '@/api/marketing/invitation'
import { getPositionListApi } from '@/api/marketing/activity'
import { formatTexarea } from '@/utils/tools'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const emit = defineEmits(['refresh'])
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  flag: {
    type: Boolean,
    default: false
  }
})

const inviterOptions = ref([])
const scrollRef = ref(null)
const formRef = ref(null)
const submit = ref(false)
const router = useRouter()
const positionOptions = ref([]) // 普通点位
const specialPositionTypeOptions = ref([]) // 特殊点位
const visible = ref(false)

const formParams = reactive({
  type: 1,
  activityName: '',
  hostCouponId: '',
  huodongshijian: '',
  rule: 1, // 规则1自动发放2主动领取
  ruleDescribe: '',
  shareTitle: '',
  shareImg: '',
  shareBackgroundImg: '',
  backgroundImg: '',
  buttonName: '',
  activityRule: '',
  cityName: '',
  position: null,
  positionIdList: null
})

/**校验点位 */
function checkPosition(rule, value, callback) {
  console.log('校验点位', value)
  if (value === 1 || value === 3) {
    callback()
  } else if (value === 2 || value === 4) {
    if (!formParams.positionIdList || !formParams.positionIdList.length) {
      callback(new Error('请选择点位'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请选择'))
  }
}

const rules = {
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  cityName: [{ required: true, message: '请选择', trigger: 'change' }],
  hostCouponId: [{ required: true, message: '请选择邀请奖励', trigger: 'blur' }],
  huodongshijian: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  ruleDescribe: [{ required: true, message: '请输入邀请好友规则', trigger: 'blur' }],
  shareTitle: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  shareImg: [{ required: true, message: '请上传图片', trigger: 'change' }],
  shareBackgroundImg: [{ required: true, message: '请上传分享页面背景', trigger: 'change' }],
  backgroundImg: [{ required: true, message: '请上传活动图片', trigger: 'change' }],
  buttonName: [{ required: true, message: '请输入按钮文字', trigger: 'blur' }],
  activityRule: [{ required: true, message: '请输入活动规则', trigger: 'blur' }],
  position: [{ required: true, validator: checkPosition, trigger: 'change' }]
}

// 禁用所有未来的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 切换城市
function handleChangeCity() {
  getOptions()
  getPositions()
  formParams.hostCouponId = ''
  formParams.position = null
  formParams.positionIdList = []
}

function onClose() {
  formRef.value.resetFields()
  const arr = [
    'type',
    'activityName',
    'hostCouponId',
    'huodongshijian',
    'rule', // 规则1自动发放2主动领取
    'ruleDescribe',
    'shareTitle',
    'shareImg',
    'shareBackgroundImg',
    'backgroundImg',
    'buttonName',
    'activityRule',
    'cityName',
    'position',
    'positionIdList'
  ]
  arr.forEach((i) => {
    formParams[i] = null
  })
  formParams.type = 1
  formParams.rule = 1
  scrollRef.value?.setScrollTop(0)
  visible.value = false
}
/**返回点位列表 */
function positionIdListMap(position) {
  // 1普通全部点位 2普通指定点位表 3特殊全部点位 4特殊指定点位
  switch (position) {
    case 1:
      return []
    case 3:
      return []
    default:
      return formParams.positionIdList
  }
}
/**切换点位 */
function positionChange(type) {
  console.log('=================')

  if (type && props.title.includes('设置')) {
    formParams.hostCouponId = ''
    formParams.positionIdList = []
    getOptions()
  } else if (!type && props.title.includes('设置')) {
    formParams.hostCouponId = ''
    getOptions()
  } else {
    formParams.positionIdList = []
    getOptions()
  }
}
function handleAction(confirm) {
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid) {
        submit.value = true
        const params = { ...formParams }
        params.shareImg = params.shareImg?.length ? params.shareImg[0].url : ''
        params.shareBackgroundImg = params.shareBackgroundImg?.length
          ? params.shareBackgroundImg[0].url
          : ''
        params.backgroundImg = params.backgroundImg?.length ? params.backgroundImg[0].url : ''
        params.startTime = params.huodongshijian?.length
          ? new Date(params.huodongshijian[0] + ':00').getTime()
          : ''
        params.endTime = params.huodongshijian?.length
          ? new Date(params.huodongshijian[1] + ':59').getTime()
          : ''
        params.activityRule = formatTexarea(formParams.activityRule)
        params.ruleDescribe = formatTexarea(formParams.ruleDescribe)
        params.positionIdList = positionIdListMap(formParams.position)
        delete params.huodongshijian
        console.log('handleAction==========', params)
        const api = props.title === '邀请活动编辑' ? editIntivationApi : addIntivationApi
        api(params)
          .then(() => {
            submit.value = false
            onClose()
            emit('refresh')
            ElMessage({
              message: `活动${props.title === '邀请活动编辑' ? '编辑' : '新建'}成功`,
              type: 'success'
            })
            if (props.flag) {
              router.push('/market/invitation')
            }
          })
          .catch(() => {
            submit.value = false
          })
      } else {
        ElMessage({
          message: '提交失败，请校验数据',
          type: 'error'
        })
      }
    })
  } else {
    onClose()
  }
}
function getPositions() {
  getPositionListApi({ cityName: formParams.cityName }).then((res) => {
    positionOptions.value = res?.data?.filter((i) => i?.label === 2)
    specialPositionTypeOptions.value = res?.data?.filter((i) => i?.label === 1)
  })
}
function getOptions() {
  // 1邀请人奖励
  getAllCouponListApi({
    cityName: formParams.cityName,
    position: formParams.position - 1,
    positionIdList: formParams.positionIdList
  }).then((res) => {
    inviterOptions.value = res?.data
      ?.filter((i) => {
        return i?.marCouponVOList?.length
      })
      .map((i) => {
        return {
          label: i.typeName,
          value: i.type,
          children: i.marCouponVOList?.map((j) => {
            return {
              label: j.remark ? `${j.couponName} / ${j.remark}` : j.couponName,
              value: j.id
            }
          })
        }
      })
  })
}

function getDetail(marActivityId) {
  getInvitationDetailApi({ marActivityId }).then((res) => {
    Object.keys(formParams).forEach((key) => {
      formParams[key] = res?.data[key]
    })
    formParams.huodongshijian = [res.data.startTime, res.data.endTime]
    formParams.shareImg = res.data.shareImg ? [{ url: res.data.shareImg }] : ''
    formParams.shareBackgroundImg = res.data.shareBackgroundImg
      ? [{ url: res.data.shareBackgroundImg }]
      : ''
    formParams.backgroundImg = res.data.backgroundImg ? [{ url: res.data.backgroundImg }] : ''
    formParams.activityRule = formatTexarea(res.data.activityRule, 1)
    formParams.ruleDescribe = formatTexarea(res.data.ruleDescribe, 1)
    formParams.id = res.data.id
    getOptions()
    visible.value = true
  })
}

function init(cityName, val) {
  formParams.cityName = cityName
  getPositions()
  if (val) {
    getDetail(val)
  } else {
    getOptions()
    visible.value = true
  }
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  transform: translate3d(0, -20px, 0);
  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
  }
}

::v-deep .el-upload-list__item {
  transition: none !important;
}
.title2 {
  font-size: 14px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
    Arial, sans-serif;
}
::v-deep .el-radio-group {
  display: block;
}
</style>
